<template>
  <div class="sales-order-detail">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
        <h2 class="page-title">销售订单详情</h2>
        <el-tag v-if="orderData.status" :type="getOrderStatusType(orderData.status)" class="order-status">
          {{ getOrderStatusText(orderData.status) }}
        </el-tag>
      </div>
      <div class="header-actions">
        <el-button @click="printOrder" :icon="Printer">打印</el-button>
        <el-button type="primary" @click="editOrder" :disabled="orderData.status === 'completed'" :icon="Edit">编辑</el-button>
      </div>
    </div>
    
    <div class="order-content" v-loading="loading">
      <!-- 基本信息卡片 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">基本信息</span>
          </div>
        </template>
        
        <div class="card-content">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="订单编号" :span="1">
              <span class="highlight">{{ orderData.id }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="创建日期" :span="1">{{ orderData.date }}</el-descriptions-item>
            <el-descriptions-item label="销售人员" :span="1">{{ orderData.salesperson }}</el-descriptions-item>
            <el-descriptions-item label="客户名称" :span="2">{{ orderData.customerName }}</el-descriptions-item>
            <el-descriptions-item label="联系方式" :span="1">{{ orderData.customerContact }}</el-descriptions-item>
            <el-descriptions-item label="付款状态" :span="1">
              <el-tag :type="getPaymentStatusType(orderData.paymentStatus)" size="small">
                {{ getPaymentStatusText(orderData.paymentStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="订单状态" :span="1">
              <el-tag :type="getOrderStatusType(orderData.status)" size="small">
                {{ getOrderStatusText(orderData.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="1">{{ orderData.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>
      
      <!-- 订单进度卡片 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">订单进度</span>
            <span class="progress-percentage">完成率: {{ calculateProgressPercentage() }}%</span>
          </div>
        </template>
        
        <div class="card-content">
          <div class="progress-container">
            <div class="progress-circle-container">
              <div class="progress-circle" ref="progressCircleRef"></div>
              <div class="progress-circle-text">{{ calculateProgressPercentage() }}%</div>
            </div>
            
            <div class="progress-steps-container">
              <el-steps :active="orderProgressStep" finish-status="success" align-center>
                <el-step title="询价" :icon="ChatLineRound" description="客户询价" />
                <el-step title="报价" :icon="Document" description="提供报价" />
                <el-step title="收款" :icon="Money" description="收到款项" />
                <el-step title="审核" :icon="Check" description="订单审核" />
                <el-step title="下达生产订单" :icon="Tickets" description="生产安排" />
                <el-step title="商品生产" :icon="SetUp" description="生产中" />
                <el-step title="商品测试" :icon="Aim" description="质量检测" />
                <el-step title="商品包装" :icon="Box" description="包装中" />
                <el-step title="商品发货" :icon="Van" description="发货中" />
                <el-step title="交易完成" :icon="CircleCheck" description="完成交易" />
              </el-steps>
            </div>
          </div>
          
          <div class="progress-info" v-if="orderData.currentStepTime">
            <el-tag type="info">
              当前阶段：{{ getCurrentStepName() }} - {{ orderData.currentStepTime }}
            </el-tag>
          </div>
        </div>
      </el-card>
      
      <!-- 商品信息卡片 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">商品信息</span>
          </div>
        </template>
        
        <div class="card-content">
          <el-table :data="orderData.products" border style="width: 100%">
            <el-table-column type="index" width="50" align="center" />
            <el-table-column prop="productCode" label="商品编码" width="120" />
            <el-table-column prop="productName" label="商品名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="specifications" label="规格" width="150" show-overflow-tooltip />
            <el-table-column prop="unit" label="单位" width="80" align="center" />
            <el-table-column prop="quantity" label="数量" width="100" align="right" />
            <el-table-column prop="price" label="单价" width="120" align="right">
              <template #default="scope">
                {{ formatCurrency(scope.row.price) }}
              </template>
            </el-table-column>
            <el-table-column prop="discount" label="折扣" width="80" align="center">
              <template #default="scope">
                {{ scope.row.discount ? (scope.row.discount * 10).toFixed(1) + '折' : '无' }}
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120" align="right">
              <template #default="scope">
                {{ formatCurrency(scope.row.price * scope.row.quantity * (scope.row.discount || 1)) }}
              </template>
            </el-table-column>
          </el-table>
          
          <div class="order-summary">
            <div class="summary-item">
              <span>商品总数:</span>
              <span>{{ orderData.products?.reduce((sum, item) => sum + item.quantity, 0) || 0 }} 件</span>
            </div>
            <div class="summary-item">
              <span>商品金额:</span>
              <span>{{ formatCurrency(calculateSubtotal()) }}</span>
            </div>
            <div class="summary-item">
              <span>税费:</span>
              <span>{{ formatCurrency(orderData.tax || 0) }}</span>
            </div>
            <div class="summary-item">
              <span>运费:</span>
              <span>{{ formatCurrency(orderData.shipping || 0) }}</span>
            </div>
            <div class="summary-item">
              <span>优惠金额:</span>
              <span class="discount-amount">-{{ formatCurrency(orderData.discount || 0) }}</span>
            </div>
            <div class="summary-item total">
              <span>订单总计:</span>
              <span class="total-amount">{{ formatCurrency(calculateTotal()) }}</span>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 支付信息卡片 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">支付信息</span>
          </div>
        </template>
        
        <div class="card-content">
          <el-table :data="orderData.payments" border style="width: 100%">
            <el-table-column prop="date" label="支付日期" width="150" />
            <el-table-column prop="method" label="支付方式" width="120">
              <template #default="scope">
                {{ getPaymentMethodText(scope.row.method) }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="支付金额" width="150" align="right">
              <template #default="scope">
                {{ formatCurrency(scope.row.amount) }}
              </template>
            </el-table-column>
            <el-table-column prop="transactionId" label="交易流水号" min-width="180" />
            <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
          </el-table>
          
          <div class="payment-summary">
            <div class="summary-item">
              <span>已支付金额:</span>
              <span>{{ formatCurrency(calculatePaidAmount()) }}</span>
            </div>
            <div class="summary-item">
              <span>应付金额:</span>
              <span>{{ formatCurrency(calculateTotal()) }}</span>
            </div>
            <div class="summary-item total">
              <span>未付金额:</span>
              <span class="unpaid-amount">{{ formatCurrency(calculateTotal() - calculatePaidAmount()) }}</span>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 物流信息卡片 -->
      <el-card class="detail-card" shadow="never" v-if="orderData.delivery">
        <template #header>
          <div class="card-header">
            <span class="card-title">物流信息</span>
          </div>
        </template>
        
        <div class="card-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="收货人" :span="1">{{ orderData.delivery.receiverName }}</el-descriptions-item>
            <el-descriptions-item label="联系电话" :span="1">{{ orderData.delivery.receiverPhone }}</el-descriptions-item>
            <el-descriptions-item label="收货地址" :span="2">{{ orderData.delivery.address }}</el-descriptions-item>
            <el-descriptions-item label="物流公司" :span="1">{{ orderData.delivery.company }}</el-descriptions-item>
            <el-descriptions-item label="物流单号" :span="1">{{ orderData.delivery.trackingNumber }}</el-descriptions-item>
            <el-descriptions-item label="发货时间" :span="1">{{ orderData.delivery.shippingDate }}</el-descriptions-item>
            <el-descriptions-item label="送达时间" :span="1">{{ orderData.delivery.deliveryDate || '未送达' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>
      
      <!-- 操作记录卡片 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">操作记录</span>
          </div>
        </template>
        
        <div class="card-content">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in orderData.activities"
              :key="index"
              :timestamp="activity.time"
              :type="getActivityType(activity.type)"
              :icon="getActivityIcon(activity.type)"
            >
              {{ activity.content }}
              <span class="operator">操作人: {{ activity.operator }}</span>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, computed, nextTick, watch, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Printer,
  Edit,
  Document,
  Money,
  Check,
  Tickets,
  SetUp,
  Aim,
  Box,
  Van,
  CircleCheck,
  ChatLineRound,
  Plus,
  Minus,
  InfoFilled,
  WarningFilled,
  CircleCheckFilled,
  Clock
} from '@element-plus/icons-vue'
import * as echarts from 'echarts/core'
import { GaugeChart } from 'echarts/charts'
import { TitleComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([TitleComponent, GaugeChart, CanvasRenderer])

// 模拟获取订单详情API
const fetchOrderDetail = async (orderId: string) => {
  console.log('获取订单详情，ID:', orderId)
  
  // 这里应该是实际的API调用
  // 模拟订单数据
  return {
    id: orderId,
    date: '2023-05-15',
    customerName: '上海星辰科技有限公司',
    customerContact: '13812345678',
    salesperson: '销售员1',
    status: 'processing',
    paymentStatus: 'partially_paid',
    remark: '客户要求尽快发货',
    tax: 1250.50,
    shipping: 300,
    discount: 2000,
    currentStep: 5, // 当前进度步骤（1-10）
    currentStepTime: '2023-05-18 14:20:00',
    products: [
      { productCode: 'P001', productName: '高级办公椅', specifications: '黑色真皮', unit: '把', quantity: 10, price: 1500, discount: 0.95 },
      { productCode: 'P002', productName: '人体工学键盘', specifications: '无线蓝牙', unit: '个', quantity: 20, price: 350, discount: 0.9 },
      { productCode: 'P003', productName: '商务笔记本电脑', specifications: '15.6英寸 i7处理器', unit: '台', quantity: 5, price: 8000, discount: 0.98 },
      { productCode: 'P004', productName: '办公文件柜', specifications: '三层', unit: '个', quantity: 8, price: 1200, discount: 1 }
    ],
    payments: [
      { date: '2023-05-15', method: 'bank_transfer', amount: 30000, transactionId: 'T20230515001', remark: '首付款' },
      { date: '2023-05-30', method: 'alipay', amount: 31950.5, transactionId: 'T20230530002', remark: '尾款' }
    ],
    delivery: {
      receiverName: '张经理',
      receiverPhone: '13987654321',
      address: '上海市浦东新区张江高科技园区科苑路88号',
      company: '顺丰速运',
      trackingNumber: 'SF1234567890',
      shippingDate: '2023-05-18',
      deliveryDate: '2023-05-20'
    },
    activities: [
      { time: '2023-05-10 09:30:00', type: 'inquiry', content: '客户询价', operator: '销售员1' },
      { time: '2023-05-12 10:15:00', type: 'quote', content: '提交报价单', operator: '销售员1' },
      { time: '2023-05-15 09:30:00', type: 'create', content: '创建订单', operator: '销售员1' },
      { time: '2023-05-15 10:15:00', type: 'payment', content: '收到首付款 ¥30,000.00', operator: '财务1' },
      { time: '2023-05-16 11:45:00', type: 'audit', content: '订单审核通过', operator: '主管1' },
      { time: '2023-05-18 14:20:00', type: 'production_order', content: '生产订单已下达', operator: '生产主管1' },
      { time: '2023-05-20 16:45:00', type: 'delivery', content: '订单发货中', operator: '仓库员1' },
      { time: '2023-05-30 11:30:00', type: 'payment', content: '收到尾款 ¥31,950.50', operator: '财务1' }
    ]
  }
}

export default defineComponent({
  name: 'SalesOrderDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 订单ID
    const orderId = computed(() => route.params.id as string)
    
    // 加载状态
    const loading = ref(false)
    
    // 进度步骤
    const orderProgressStep = ref(0)
    
    // 订单数据
    const orderData = ref({
      id: '',
      date: '',
      customerName: '',
      customerContact: '',
      salesperson: '',
      status: '',
      paymentStatus: '',
      remark: '',
      tax: 0,
      shipping: 0,
      discount: 0,
      currentStep: 0,
      currentStepTime: '',
      products: [] as any[],
      payments: [] as any[],
      delivery: null as any,
      activities: [] as any[]
    })
    
    const progressCircleRef = ref<HTMLElement | null>(null)
    let progressChart: echarts.ECharts | null = null
    
    // 获取订单详情
    const getOrderDetail = async () => {
      if (!orderId.value) return
      
      loading.value = true
      
      try {
        const data = await fetchOrderDetail(orderId.value)
        orderData.value = data
        orderProgressStep.value = data.currentStep
        
        // 初始化进度图表
        nextTick(() => {
          initProgressChart()
        })
      } catch (error) {
        console.error('获取订单详情失败:', error)
        ElMessage.error('获取订单详情失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 初始化进度图表
    const initProgressChart = () => {
      if (!progressCircleRef.value) return
      
      progressChart = echarts.init(progressCircleRef.value)
      updateProgressChart()
      
      window.addEventListener('resize', handleResize)
    }
    
    // 更新进度图表
    const updateProgressChart = () => {
      if (!progressChart) return
      
      const option = {
        series: [
          {
            type: 'gauge',
            startAngle: 90,
            endAngle: -270,
            pointer: {
              show: false
            },
            progress: {
              show: true,
              overlap: false,
              roundCap: true,
              clip: false,
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#67C23A'
                    },
                    {
                      offset: 1,
                      color: '#409EFF'
                    }
                  ]
                }
              }
            },
            axisLine: {
              lineStyle: {
                width: 15,
                color: [[1, '#E5E7EB']]
              }
            },
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              show: false
            },
            anchor: {
              show: false
            },
            title: {
              show: false
            },
            detail: {
              show: false
            },
            data: [
              {
                value: calculateProgressPercentage()
              }
            ]
          }
        ]
      }
      
      progressChart.setOption(option)
    }
    
    // 处理窗口大小变化
    const handleResize = () => {
      progressChart?.resize()
    }
    
    // 计算进度百分比
    const calculateProgressPercentage = () => {
      // 总共10个步骤，计算百分比
      return Math.ceil(((orderProgressStep.value) / 10) * 100)
    }
    
    // 获取当前步骤名称
    const getCurrentStepName = () => {
      const steps = [
        '询价', '报价', '收款', '审核', '下达生产订单',
        '商品生产', '商品测试', '商品包装', '商品发货', '交易完成'
      ]
      return steps[orderData.value.currentStep - 1] || ''
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 打印订单
    const printOrder = () => {
      ElMessage.success('打印功能待实现')
    }
    
    // 编辑订单
    const editOrder = () => {
      router.push(`/yxerp/sales/order/edit/${orderId.value}`)
    }
    
    // 计算商品小计
    const calculateSubtotal = () => {
      if (!orderData.value.products || !orderData.value.products.length) return 0
      
      return orderData.value.products.reduce((sum, item) => {
        const discount = item.discount || 1
        return sum + (item.price * item.quantity * discount)
      }, 0)
    }
    
    // 计算订单总计
    const calculateTotal = () => {
      const subtotal = calculateSubtotal()
      const tax = orderData.value.tax || 0
      const shipping = orderData.value.shipping || 0
      const discount = orderData.value.discount || 0
      
      return subtotal + tax + shipping - discount
    }
    
    // 计算已支付金额
    const calculatePaidAmount = () => {
      if (!orderData.value.payments || !orderData.value.payments.length) return 0
      
      return orderData.value.payments.reduce((sum, payment) => sum + payment.amount, 0)
    }
    
    // 格式化货币
    const formatCurrency = (value: number) => {
      return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(value)
    }
    
    // 获取付款状态类型
    const getPaymentStatusType = (status: string) => {
      switch (status) {
        case 'paid': return 'success'
        case 'partially_paid': return 'warning'
        case 'unpaid': return 'danger'
        default: return 'info'
      }
    }
    
    // 获取付款状态文本
    const getPaymentStatusText = (status: string) => {
      switch (status) {
        case 'paid': return '已付款'
        case 'partially_paid': return '部分付款'
        case 'unpaid': return '未付款'
        default: return '未知'
      }
    }
    
    // 获取订单状态类型
    const getOrderStatusType = (status: string) => {
      switch (status) {
        case 'completed': return 'success'
        case 'processing': return 'primary'
        case 'pending': return 'warning'
        case 'cancelled': return 'info'
        default: return 'info'
      }
    }
    
    // 获取订单状态文本
    const getOrderStatusText = (status: string) => {
      switch (status) {
        case 'completed': return '已完成'
        case 'processing': return '处理中'
        case 'pending': return '待处理'
        case 'cancelled': return '已取消'
        default: return '未知'
      }
    }
    
    // 获取支付方式文本
    const getPaymentMethodText = (method: string) => {
      switch (method) {
        case 'cash': return '现金'
        case 'bank_transfer': return '银行转账'
        case 'alipay': return '支付宝'
        case 'wechat': return '微信支付'
        case 'credit_card': return '信用卡'
        default: return '其他'
      }
    }
    
    // 获取活动类型
    const getActivityType = (type: string) => {
      switch (type) {
        case 'inquiry': return 'info'
        case 'quote': return 'info'
        case 'create': return 'primary'
        case 'payment': return 'success'
        case 'audit': return 'warning'
        case 'production_order': return 'warning'
        case 'production': return 'warning'
        case 'testing': return 'warning'
        case 'packaging': return 'warning'
        case 'shipping': return 'warning'
        case 'delivery': return 'info'
        case 'complete': return 'success'
        default: return 'info'
      }
    }
    
    // 获取活动图标
    const getActivityIcon = (type: string) => {
      switch (type) {
        case 'inquiry': return ChatLineRound
        case 'quote': return Document
        case 'create': return Plus
        case 'payment': return Money
        case 'audit': return Check
        case 'production_order': return Tickets
        case 'production': return SetUp
        case 'testing': return Aim
        case 'packaging': return Box
        case 'shipping': return Van
        case 'delivery': return Van
        case 'complete': return CircleCheck
        default: return InfoFilled
      }
    }
    
    // 监听进度步骤变化，更新图表
    watch(
      () => orderProgressStep.value,
      () => {
        nextTick(() => {
          updateProgressChart()
        })
      }
    )
    
    // 组件挂载时获取订单详情
    onMounted(() => {
      getOrderDetail()
    })
    
    // 组件卸载时销毁图表实例
    onUnmounted(() => {
      if (progressChart) {
        progressChart.dispose()
        progressChart = null
      }
      window.removeEventListener('resize', handleResize)
    })
    
    return {
      orderId,
      loading,
      orderData,
      orderProgressStep,
      goBack,
      printOrder,
      editOrder,
      calculateSubtotal,
      calculateTotal,
      calculatePaidAmount,
      formatCurrency,
      getPaymentStatusType,
      getPaymentStatusText,
      getOrderStatusType,
      getOrderStatusText,
      getPaymentMethodText,
      getActivityType,
      getActivityIcon,
      getCurrentStepName,
      calculateProgressPercentage,
      // 图标
      ArrowLeft,
      Printer,
      Edit,
      Document,
      Money,
      Check,
      Tickets,
      SetUp,
      Aim,
      Box,
      Van,
      CircleCheck,
      ChatLineRound,
      progressCircleRef
    }
  }
})
</script>

<style scoped lang="scss">
.sales-order-detail {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 15px;
      
      .page-title {
        margin: 0;
        font-size: 22px;
        font-weight: 600;
        color: #303133;
      }
      
      .order-status {
        font-size: 14px;
      }
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .order-content {
    .detail-card {
      margin-bottom: 20px;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .card-title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
        
        .progress-percentage {
          font-size: 14px;
          color: #67C23A;
          font-weight: 500;
        }
      }
      
      .card-content {
        .highlight {
          color: #409EFF;
          font-weight: 500;
        }
        
        .progress-container {
          display: flex;
          align-items: center;
          gap: 30px;
          margin-bottom: 20px;
          
          .progress-circle-container {
            position: relative;
            width: 120px;
            height: 120px;
            flex-shrink: 0;
            
            .progress-circle {
              width: 100%;
              height: 100%;
            }
            
            .progress-circle-text {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              font-size: 20px;
              font-weight: 700;
              color: #67C23A;
            }
          }
          
          .progress-steps-container {
            flex: 1;
          }
        }
        
        .progress-info {
          margin-top: 20px;
          text-align: center;
        }
        
        .order-summary, .payment-summary {
          margin-top: 20px;
          padding: 15px;
          background-color: #f8f9fa;
          border-radius: 4px;
          
          .summary-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            span:first-child {
              color: #606266;
            }
            
            &.total {
              margin-top: 12px;
              padding-top: 12px;
              border-top: 1px dashed #dcdfe6;
              font-size: 16px;
              font-weight: 600;
              
              span {
                color: #303133;
              }
            }
            
            .discount-amount {
              color: #F56C6C;
            }
            
            .total-amount {
              color: #F56C6C;
              font-size: 18px;
            }
            
            .unpaid-amount {
              color: #F56C6C;
            }
          }
        }
        
        .operator {
          margin-left: 10px;
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }
}
</style> 